<template>
  <div class="bg-white p-4 rounded-lg flex flex-col h-full overflow-hidden">
    <!-- 标题栏组件 -->
    <MemberTableHeader
      :total-count="totalCount"
      :current-page-count="tableData.length"
      :has-active-filters="hasActiveFilters"
      :has-active-sorter="hasActiveSorter"
      :show-controls="showControls"
      @toggle-controls="toggleControls"
    />

    <!-- 控制面板区域组件 -->
    <MemberTableControls
      :show-controls="showControls"
      :scroll-position="scrollPosition"
      :filters="filters"
      :filter-options="filterOptions"
      :search-query="searchQuery"
      :sort-state="sortState"
      :visible-columns="visibleColumns"
      :base-columns="baseColumns"
      :show-add-modal="showAddModal"
      :show-batch-import-modal="showBatchImportModal"
      @update:scroll-position="handleScrollPositionUpdate"
      @update:filters="handleFiltersUpdate"
      @update:search-query="handleSearchQueryUpdate"
      @update:visible-columns="handleVisibleColumnsUpdate"
      @scroll-left="scrollToLeft"
      @scroll-right="scrollToRight"
      @scroll-center="scrollToCenter"
      @handle-scroll-slider="handleScrollSlider"
      @handle-filter-change="handleFilterChange"
      @handle-search-change="handleSearchQueryUpdate"
      @handle-sort-click="handleSortClick"
      @clear-all-filters="clearAllFilters"
      @update:show-add-modal="showAddModal = $event"
      @update:show-batch-import-modal="showBatchImportModal = $event"
    />

    <!-- 表格容器区域组件 -->
    <MemberTable
      ref="tableRef"
      :table-data="tableData"
      :pagination="pagination"
      :loading="loading"
      :base-columns="baseColumns"
      :visible-columns="visibleColumns"
      @view-details="handleViewDetails"
      @delete-member="handleDeleteMember"
      @table-scroll="handleTableScroll"
    />

    <!-- 新增党员模态框组件 -->
    <AddMemberModal
      :show="showAddModal"
      @update:show="showAddModal = $event"
      @success="handleAddSuccess"
    />

    <!-- 批量导入模态框组件 -->
    <BatchImportModal
      :show="showBatchImportModal"
      @update:show="showBatchImportModal = $event"
      @import-success="handleImportSuccess"
    />
  </div>
</template>

<script setup>
// ==================== 导入依赖 ====================
import { useRouter } from 'vue-router'
import { ref, onMounted, computed, watch, nextTick } from 'vue'
import { useDialog, useMessage } from 'naive-ui'

// 导入拆分后的组件
import MemberTableHeader from './MemberTableHeader.vue'
import MemberTableControls from './MemberTableControls.vue'
import MemberTable from './MemberTable.vue'
import AddMemberModal from './AddMemberModal.vue'
import BatchImportModal from './BatchImportModal.vue'

// ======== 接入后端 API（前面我给你的 src/api 实现） ========
import {
  fetchMemberList as apiFetchMemberList,
  deleteMember,
  fetchFilterOptions
} from '@/api'

// ==================== 基础实例 ====================
const router = useRouter()
const dialog = useDialog()
const message = useMessage()
const tableRef = ref(null)

// ==================== 界面控制相关响应式数据 ====================
const showControls = ref(true) // 控制面板显示/隐藏
const loading = ref(false) // 加载状态
const scrollPosition = ref(0) // 横向滚动位置

// ==================== 数据相关响应式数据 ====================
const allData = ref([]) // 所有数据（如需导出/汇总可使用）
const tableData = ref([]) // 表格显示数据
const totalCount = ref(0) // 总数据量
const searchQuery = ref('') // 搜索关键词
const sortState = ref('default') // 'default' | 'asc' | 'desc'

// ==================== 筛选和排序相关响应式数据 ====================
// 筛选条件状态 - 对应接口文档中的筛选字段
const filters = ref({
  genderType: '',        // 性别筛选
  politicalStatus: '',   // 政治面貌筛选
  studentClass: '',      // 班级筛选
  majorField: '',        // 专业筛选
  educationLevel: '',    // 学历层次筛选
  enrollmentStatus: ''   // 学籍状态筛选
})

// 排序按钮展示
const sortButtonText = computed(() => {
  switch (sortState.value) {
    case 'asc':
      return '学号升序';
    case 'desc':
      return '学号降序';
    default:
      return '默认排序';
  }
});

const sortOrder = computed(() => {
  if (sortState.value === 'asc') return 'asc'
  if (sortState.value === 'desc') return 'desc'
  return null
})

const handleSortClick = () => {
  if (sortState.value === 'default') {
    sortState.value = 'asc';
  } else if (sortState.value === 'asc') {
    sortState.value = 'desc';
  } else {
    sortState.value = 'default';
  }
  pagination.value.page = 1; // 重置到第一页
  loadData();
};

// 筛选选项数据（来自 /api/member/filter-options）
const filterOptions = ref({
  genderType: [],
  studentClass: [],
  majorField: [],
  enrollmentStatus: [],
  politicalStatus: []
})

// ==================== 模态框相关响应式数据 ====================
const showAddModal = ref(false) // 新增模态框显示状态
const showBatchImportModal = ref(false) // 批量导入模态框显示状态

// ==================== 分页配置 ====================
const pagination = ref({
  page: 1,
  pageSize: 20,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100],
  itemCount: 0,
  prefix: ({ itemCount }) => `共 ${itemCount} 条`,
  onChange: (page) => {
    pagination.value.page = page
    loadData()
  },
  onUpdatePageSize: (pageSize) => {
    pagination.value.pageSize = pageSize
    pagination.value.page = 1
    loadData()
  },
})

// ==================== 表格列定义 ====================
// 基础列配置：按照从基本信息到党员档案发展顺序排列
const baseColumns = [
  // === 基本信息部分 ===
  {
    title: '姓名',
    key: 'memberName',
    width: 100,
    fixed: 'left'
  },
  {
    title: '性别',
    key: 'genderType',
    width: 80
  },
  {
    title: '民族',
    key: 'nationalityDesc',
    width: 80
  },
  {
    title: '学号',
    key: 'studentId',
    width: 120
  },
  {
    title: '班级',
    key: 'studentClass',
    width: 180
  },
  {
    title: '专业',
    key: 'majorField',
    width: 180
  },
  {
    title: '学历层次',
    key: 'educationLevel',
    width: 100
  },
  {
    title: '年级',
    key: 'gradeLevel',
    width: 80
  },
  {
    title: '学籍状态',
    key: 'enrollmentStatus',
    width: 100
  },
  {
    title: '籍贯',
    key: 'birthPlace',
    width: 120
  },
  {
    title: '出生日期',
    key: 'birthDate',
    width: 120
  },
  {
    title: '身份证号',
    key: 'idCardNumber',
    width: 180
  },
  {
    title: '入学年月',
    key: 'enrollmentDate',
    width: 120
  },
  {
    title: '手机号',
    key: 'phoneNumber',
    width: 130
  },
  {
    title: '寝室',
    key: 'dormitoryRoom',
    width: 100
  },
  {
    title: '导师',
    key: 'advisorName',
    width: 100
  },
  {
    title: '政治面貌',
    key: 'politicalStatus',
    width: 120
  },
  {
    title: '当前所在党支部',
    key: 'currentPartyBranch',
    width: 200
  },
  {
    title: '备注',
    key: 'memberRemarks',
    width: 150
  },
  {
    title: '入团时间',
    key: 'joinLeagueDate',
    width: 120
  },

  // === 党员发展阶段信息 ===
  {
    title: '申请入党时间',
    key: 'applicationDate',
    width: 130
  },
  {
    title: '谈心谈话时间',
    key: 'heartToHeartTalkDate',
    width: 130
  },
  {
    title: '团推优时间',
    key: 'branchRecommendDate',
    width: 120
  },
  {
    title: '确定积极分子时间',
    key: 'activistDesignationDate',
    width: 150
  },
  {
    title: '积极分子培训时间',
    key: 'trainingDate',
    width: 150
  },
  {
    title: '积极分子思想汇报数量',
    key: 'activistThoughtReportCount',
    width: 180
  },
  {
    title: '培养联系人',
    key: 'mentorNames',
    width: 120
  },
  {
    title: '群众意见时间',
    key: 'massOpinionDate',
    width: 130
  },
  {
    title: '自传时间',
    key: 'autobiographyDate',
    width: 120
  },
  {
    title: '确定发展对象时间',
    key: 'developmentTargetDate',
    width: 150
  },
  {
    title: '外调材料日期',
    key: 'externalInvestigationDate',
    width: 130
  },
  {
    title: '政审材料日期',
    key: 'comprehensiveReviewDate',
    width: 130
  },
  {
    title: '发展对象培训时间',
    key: 'developmentTrainingDate',
    width: 150
  },
  {
    title: '入党时间',
    key: 'probationaryAcceptanceDate',
    width: 120
  },
  {
    title: '入党志愿书编号',
    key: 'volunteerIdNumber',
    width: 140
  },
  {
    title: '入党总支审查日期',
    key: 'generalBranchReviewDate',
    width: 150
  },
  {
    title: '发展党员上级组织谈话日期',
    key: 'designatedTalkDate',
    width: 200
  },
  {
    title: '入党上级党委审批日期',
    key: 'baseCommitteeApprovalDate',
    width: 180
  },
  {
    title: '转正申请书时间',
    key: 'conversionApplicationDate',
    width: 150
  },
  {
    title: '转正公示日期',
    key: 'conversionPublicityDate',
    width: 130
  },
  {
    title: '转正大会时间',
    key: 'conversionMeetingDate',
    width: 130
  },
  {
    title: '转正党总支意见',
    key: 'conversionGeneralBranchOpinion',
    width: 150
  },
  {
    title: '转正上级党委审批日期',
    key: 'conversionCommitteeApprovalDate',
    width: 180
  },

  // === 统计信息 ===
  {
    title: '参与活动数量',
    key: 'volunteerActivityCount',
    width: 130
  },
  {
    title: '所获奖项数量',
    key: 'awardsReceivedCount',
    width: 130
  },
  {
    title: '政审外调数量',
    key: 'externalInvestigationCount',
    width: 130
  },

  // === 操作列 ===
  {
    title: '操作',
    key: 'actions',
    fixed: 'right',
    width: 150
  }
]

// 可见列控制
const visibleColumns = ref(baseColumns.map(col => col.key))

// ==================== 计算属性 ====================
// 检查是否有激活的筛选条件
const hasActiveFilters = computed(() => {
  return Object.values(filters.value).some(value => value !== '')
})

// 检查是否有激活的排序
const hasActiveSorter = computed(() => {
  return sortState.value !== 'default'
})

// ==================== API 接口调用函数 ====================

/**
 * 获取基础筛选选项（不含统计）
 * 对应接口：POST /api/member/filter-options
 */
const fetchFilterOptionsWithCounts = async () => {
  try {
    const data = await fetchFilterOptions()
    // 直接使用后端提供的 {label, value} 数组
    return {
      genderType: data.genderType || [],
      studentClass: data.studentClass || [],
      majorField: data.majorField || [],
      enrollmentStatus: data.enrollmentStatus || [],
      politicalStatus: data.politicalStatus || [],
      // 学历层次选项，接口未提供，手动添加
      educationLevel: [
        { label: "本科", value: "本科" },
        { label: "硕士", value: "硕士" },
        { label: "博士", value: "博士" }
      ]
    }
  } catch (error) {
    console.error('获取筛选选项失败:', error)
    return {
      genderType: [],
      studentClass: [],
      majorField: [],
      enrollmentStatus: [],
      politicalStatus: [],
      educationLevel: [
        { label: "本科", value: "本科" },
        { label: "硕士", value: "硕士" },
        { label: "博士", value: "博士" }
      ]
    }
  }
}

/**
 * 获取党员列表（分页+筛选+排序）
 * 对应接口：POST /api/member/list
 */
const fetchMemberList = async (params) => {
  try {
    const data = await apiFetchMemberList(params)
    // data: { list, total, page, pageSize }
    const listProcessed = processRawData(data.list || [])
    return { list: listProcessed, total: data.total ?? 0, page: data.page, pageSize: data.pageSize }
  } catch (error) {
    console.error('获取党员列表失败:', error)
    return { list: [], total: 0, page: 1, pageSize: 20 }
  }
}

// ==================== 数据处理函数 ====================
// 处理原始数据，计算派生字段
const processRawData = (rawData) => {
  return rawData.map(item => ({
    ...item,
    // 计算各种数量字段
    volunteerActivityCount: item.volunteerActivities?.length || 0,
    awardsReceivedCount: item.awardsReceived?.length || 0,
    activistThoughtReportCount: item.activistThoughtReports?.length || 0,
    externalInvestigationCount: item.externalInvestigations?.length || 0,
    
    // 提取日期字段
    applicationDate: item.applicationForm?.signatureDate || '-',
    heartToHeartTalkDate: item.heartToHeartTalk?.signatureDate || '-',
    activistDesignationDate: item.activistAssessment?.activistDesignationDate || '-',
    massOpinionDate: item.massOpinion?.signatureDate || '-',
    autobiographyDate: item.autobiography?.signatureDate || '-',
    probationaryAcceptanceDate: item.probationaryAcceptanceVoting?.signatureDate || '-',
    conversionApplicationDate: item.conversionApplication?.signatureDate || '-',
    
    // 提取其他复杂字段
    branchRecommendDate: item.activistRecommendation?.branchRecommendDate || '-',
    trainingDate: item.activistAssessment?.trainingStartDate || '-',
    mentorNames: item.activistAssessment?.mentorList?.map(m => m.mentorName).join('、') || '-',
    developmentTargetDate: item.activistRecommendation?.developmentTargetDate || '-',
    externalInvestigationDate: item.externalInvestigations?.[0]?.signatureDate || '-',
    comprehensiveReviewDate: item.comprehensiveReview?.signatureDate || '-',
    developmentTrainingDate: item.activistAssessment?.developmentTrainingStartDate || '-',
    volunteerIdNumber: item.applicationVolunteer?.idNumber || '-',
    generalBranchReviewDate: item.applicationVolunteer?.generalBranchReviewDate || '-',
    designatedTalkDate: item.applicationVolunteer?.designatedTalkDate || '-',
    baseCommitteeApprovalDate: item.applicationVolunteer?.baseCommitteeApprovalOpinionDate || '-',
    conversionPublicityDate: item.conversionPublicity?.startDate || '-',
    conversionMeetingDate: item.conversionVotingSummary?.signatureDate || '-',
    conversionGeneralBranchOpinion: item.applicationVolunteer?.generalBranchReviewProbationDate || '-',
    conversionCommitteeApprovalDate: item.applicationVolunteer?.baseCommitteeReviewProbationDate || '-'
  }))
}

// ==================== 筛选和排序处理函数 ====================

/**
 * 处理筛选条件变化
 */
const handleFilterChange = () => {
  pagination.value.page = 1 // 重置到第一页
  loadData()
}


/**
 * 处理搜索变化（防抖处理）
 */
const handleSearchChange = () => {
  // 这里可以添加防抖逻辑
  pagination.value.page = 1
  loadData()
}

/**
 * 清除所有筛选条件
 */
const clearAllFilters = () => {
  // 重置筛选条件
  filters.value = {
    genderType: '',
    politicalStatus: '',
    studentClass: '',
    majorField: '',
    educationLevel: '',
    enrollmentStatus: ''
  }
  
  // 重置排序
  sortState.value = 'default'
  
  // 重置搜索
  searchQuery.value = ''
  
  // 重新加载数据
  pagination.value.page = 1
  loadData()
}

// ==================== 横向滚动控制函数 ====================
const scrollToLeft = async () => {
  if (tableRef.value) {
    tableRef.value.scrollToLeft()
  }
}

const scrollToRight = async () => {
  if (tableRef.value) {
    tableRef.value.scrollToRight()
  }
}

const scrollToCenter = async () => {
  if (tableRef.value) {
    tableRef.value.scrollToCenter()
  }
}

const handleScrollSlider = async (value) => {
  await nextTick()
  const tableElement = getTableScrollElement()
  if (tableElement) {
    const maxScrollLeft = tableElement.scrollWidth - tableElement.clientWidth
    const targetScrollLeft = (maxScrollLeft * value) / 100
    tableElement.scrollTo({ left: targetScrollLeft })
  }
}

const getTableScrollElement = () => {
  if (!tableRef.value) return null
  return tableRef.value.getTableScrollElement()
}

const handleTableScroll = (e) => {
  const element = e.target
  if (element.scrollWidth > element.clientWidth) {
    const scrollPercentage = (element.scrollLeft / (element.scrollWidth - element.clientWidth)) * 100
    scrollPosition.value = Math.round(scrollPercentage)
  }
}

// ==================== 表格操作函数 ====================
const handleViewDetails = (member) => {
  router.push({
    name: 'member-detail',
    params: { id: member.memberId } // ← 使用后端的 memberId
  })
}

// ==================== 删除党员 ====================
const handleDeleteMember = (member) => {
  dialog.warning({
    title: '确认删除',
    content: `确定要删除党员 "${member.memberName}" (学号: ${member.studentId}) 吗？此操作不可撤销。`,
    positiveText: '确认删除',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        await deleteMember(member.memberId)
        message.success('删除党员成功')
        await loadData()
      } catch (error) {
        console.error('删除党员失败:', error)
        const msg = error?.response?.message || error.message || '删除党员失败，请稍后重试'
        message.error(msg)
      }
    }
  })
}

// ==================== 模态框事件处理 ====================
const handleAddSuccess = () => {
  message.success('新增党员成功')
  loadData()
}

const handleImportSuccess = () => {
  message.success('批量导入成功')
  loadData()
}

// ==================== 控制面板切换 ====================
const toggleControls = () => {
  showControls.value = !showControls.value
}

// ==================== 事件处理方法 ====================
const handleScrollPositionUpdate = (value) => {
  scrollPosition.value = value
}

const handleFiltersUpdate = (newFilters) => {
  filters.value = newFilters
  handleFilterChange()
}

const handleSearchQueryUpdate = (value) => {
  searchQuery.value = value
  // handleSearchChange()  // 这里不需要调用，因为已经有 watch 监听 searchQuery 变化
}

const handleVisibleColumnsUpdate = (value) => {
  visibleColumns.value = value
}

// ==================== 数据加载函数 ====================

/**
 * 加载党员列表数据
 * 整合搜索、筛选、排序、分页功能
 */
const loadData = async () => {
  loading.value = true
  try {
    // 构建请求参数，符合接口文档格式
    // 只传递接口文档中支持的筛选字段
    const params = {
      page: pagination.value.page,
      pageSize: pagination.value.pageSize,
      search: searchQuery.value || '',
      filters: {},
      sorter: hasActiveSorter.value
        ? { field: 'studentId', order: sortOrder.value }
        : undefined
    }
    
    // 只添加有值的筛选条件
    if (filters.value.genderType) {
      params.filters.genderType = filters.value.genderType
    }
    if (filters.value.politicalStatus) {
      params.filters.politicalStatus = filters.value.politicalStatus
    }
    if (filters.value.studentClass) {
      params.filters.studentClass = filters.value.studentClass
    }
    if (filters.value.majorField) {
      params.filters.majorField = filters.value.majorField
    }
    if (filters.value.educationLevel) {
      params.filters.educationLevel = filters.value.educationLevel
    }
    if (filters.value.enrollmentStatus) {
      params.filters.enrollmentStatus = filters.value.enrollmentStatus
    }
    
    console.log('发送请求参数:', params)
    
    const result = await fetchMemberList(params)
    tableData.value = result.list
    totalCount.value = result.total
    pagination.value.itemCount = result.total
  } catch (error) {
    console.error('加载数据失败:', error)
    tableData.value = []
    totalCount.value = 0
    pagination.value.itemCount = 0
    const msg = error?.response?.message || error.message || '加载数据失败，请稍后重试'
    message.error(msg)
  } finally {
    loading.value = false
  }
}

/**
 * 初始化筛选选项
 */
const initializeFilterOptions = async () => {
  try {
    const options = await fetchFilterOptionsWithCounts()
    filterOptions.value = {
      genderType: options.genderType || [],
      studentClass: options.studentClass || [],
      majorField: options.majorField || [],
      enrollmentStatus: options.enrollmentStatus || [],
      politicalStatus: options.politicalStatus || [],
      educationLevel: options.educationLevel || []
    }
  } catch (error) {
    console.error('初始化筛选选项失败:', error)
    message.error('获取筛选选项失败，请刷新页面重试')
  }
}

// ==================== 监听器 ====================
// 监听搜索查询变化（防抖处理）
let searchTimer = null
watch(searchQuery, (newValue, oldValue) => {
  // 只有当搜索值真正改变时才触发搜索
  if (newValue !== oldValue) {
    if (searchTimer) {
      clearTimeout(searchTimer)
    }
    searchTimer = setTimeout(() => {
      pagination.value.page = 1
      loadData()
    }, 500) // 500ms 防抖
  }
})

// ==================== 生命周期 ====================
onMounted(async () => {
  await initializeFilterOptions()
  await loadData()
})

// ==================== 组件暴露方法 ====================
defineExpose({
  refresh: loadData,
  clearAllFilters,
  scrollToLeft,
  scrollToRight,
  scrollToCenter,
  fetchFilterOptionsWithCounts,
  fetchMemberList
})
</script>

<style scoped>
/* ==================== 基础样式 ==================== */
/* 确保页面不会有整体滚动轴 */
</style>
